package com.jiuli.liping.service.impl;

import com.jiuli.liping.dao.ClassificationDao;
import com.jiuli.liping.dao.PictureDao;
import com.jiuli.liping.dao.ProductDao;
import com.jiuli.liping.dao.ShoppingCartDao;
import com.jiuli.liping.util.DateUtils;
import com.jiuli.liping.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.jiuli.liping.service.ProductService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Author zyl
 * Date  2020-03-14
 */
@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductDao productDao;

    @Autowired
    private PictureDao pictureDao;

    @Autowired
    private ShoppingCartDao shoppingCartDao;

    @Autowired
    private ClassificationDao classificationDao;

    @Autowired
    private FileManageServiceImpl fileManageServiceImpl;

    @Value("${file_hostpath}")
    private String fileHostPath;

    @Value("${filepath}")
    private String filePath;

    @Override
    public Product get(String id){
        return productDao.get(id);
    }
    
    @Override
    public List<Product> findList(Product product) {
        return productDao.findList(product);
    }
    
    @Override
    public List<Product> findAllList() {
        return productDao.findAllList();
    }
    
    @Override
    public int insert(Product product) {
        return productDao.insert(product);
    }
    
    @Override
    public int insertBatch(List<Product> products){
        return productDao.insertBatch(products);
    }
    
    @Override
    public int update(Product product) {
        return productDao.update(product);
    }
    
    @Override
    @Transactional
    public int delete(Product product) {
        Picture pi = new Picture();
        pi.setProductId(product.getProductId());
        pictureDao.deleteByproId(pi);
        return productDao.delete(product);
    }

    @Override
    @Transactional
    public Message insertProduct(Product product) {
        Message mess = new Message();
        //保存商品基本信息
        long str = System.currentTimeMillis();
        product.setProductNum("RK"+str);
        Timestamp curDate = new Timestamp(System.currentTimeMillis());
        product.setCreateTime(curDate);
        product.setFbk3(product.getAmount());//初始化入库数量，之后根据购买数产生变化
        //插入一个默认图片
        if(product.getFileList()!=null) {
            if (product.getFileList().size() > 0) {
                product.setPicture(filePath + product.getFileList().get(0));
            }
        }
        int a = productDao.insert(product);
        if(a==1){
            //插入成功,图片存到picture表
            Product newPro = productDao.getByName(product);//根据商品编号拿到主键id
            for (String url: product.getFileList()) {
                Picture pi = new Picture();
                pi.setPictureUrl(filePath+url);
                pi.setProductId(newPro.getProductId());
                pictureDao.insert(pi);
            }
            mess.setFlag("success");
            mess.setMessage("商品发布成功");
        }else {
            mess.setFlag("failed");
            mess.setMessage("商品发布失败");
        }
        return mess;
    }

    @Override
    public ProductDetail getDetail() {
        ProductDetail productDetail=new ProductDetail();
        String status = "10";
        List<Supplier> supplier = productDao.getSupplier(status);//获取所有供货商
        status = "20";
        List<Supplier> supplier2 = productDao.getSupplier(status);//获取单位
        status = "30";
        List<Supplier> supplier3 = productDao.getSupplier(status);//获取搜索数据加载
        List<ClassificationBean> classification = productDao.getClassification();//获取商品分类
        productDetail.setClassification(classification);
        productDetail.setSupplier(supplier);
        productDetail.setUnit(supplier2);
        productDetail.setSelectName(supplier3);
        productDetail.setFlag("success");
        productDetail.setMessage("获取成功");
        return productDetail;
    }

    @Override
    @Transactional
    public Message updateProduct(Product product) {
        Message mess = new Message();
        //插入一个默认图片
        if(product.getFileList()!=null) {
            if (product.getFileList().size() > 0) {
                product.setPicture(filePath + product.getFileList().get(0));
            }
        }
        //找到原有商品信息，入库数量更改，现有库存更改，然后记录更改的人
        Product newProduct = productDao.getProductInfo(product);
        if(Integer.parseInt(product.getFbk3()) < Integer.parseInt(newProduct.getFbk4())){
            mess.setFlag("failed");
            mess.setMessage("修改的数量小于将要提取的数量");
            return mess;
        }
        //当前总库存amount
        int amount = Integer.parseInt(product.getFbk3())-Integer.parseInt(newProduct.getFbk3())+Integer.parseInt(newProduct.getAmount());
        product.setAmount(amount+"");
        //插入更改记录
        product.setChangeUser(product.getCreateUser());
        Timestamp ts = new Timestamp(System.currentTimeMillis());
        product.setChangeTime(ts);
        //变更库存
        int fbk5 = Integer.parseInt(product.getFbk3())-Integer.parseInt(newProduct.getFbk3());
        product.setFbk5(fbk5+"");
        int b = productDao.insertProductChange(product);
        //更新商品信息
        int a = productDao.updateProduct(product);
        if(a==1){
            //先删除所有改商品图片
            Picture de = new Picture();
            de.setProductId(product.getProductId());
            pictureDao.deleteByproId(de);
            //插入成功,图片存到picture表
            for (String url: product.getFileList()) {
                Picture pi = new Picture();
                pi.setPictureUrl(filePath+url);
                pi.setProductId(product.getProductId());
                pictureDao.insert(pi);
            }
            mess.setFlag("success");
            mess.setMessage("商品更新成功");
        }else {
            mess.setFlag("failed");
            mess.setMessage("商品更新失败");
        }
        return mess;
    }

    @Override
    public List<Product> getProductList() {
        List<Product> prolist = productDao.getProductList();
        for (Product pro: prolist) {
            Classification cl = classificationDao.getFirstId(pro.getPid());
            pro.setId(cl.getPid()+"");
            String nowAmount = Integer.parseInt(pro.getFbk3())-Integer.parseInt(pro.getFbk4())+"";
            pro.setNowAmount(nowAmount);
        }
        return prolist;
    }

    @Override
    public Product getProductInfo(Product product) {
        Product pr = productDao.getProductInfo(product);
        pr.setFbk3Int(Integer.parseInt(pr.getFbk3())-Integer.parseInt(pr.getFbk4()));
        ShoppingCart sh = new ShoppingCart();
        sh.setUserNum(product.getUserId());
        List<ShoppingCart> list = shoppingCartDao.findAllCartListByNumber(sh);
        if(list!=null){
            pr.setCartNumber(list.size());
        }
        String nowAmount = Integer.parseInt(pr.getFbk3())-Integer.parseInt(pr.getFbk4())+"";
        pr.setNowAmount(nowAmount);
        return pr;
    }

    @Override
    public List<Product> getProductByName(Product product) {
        List<Product> list = productDao.getProductByName(product);
        for (Product pro: list) {
            Classification cl = classificationDao.getFirstId(pro.getPid());
            pro.setId(cl.getPid()+"");
            String nowAmount = Integer.parseInt(pro.getFbk3())-Integer.parseInt(pro.getFbk4())+"";
            pro.setNowAmount(nowAmount);
        }
        return list;
    }

    @Override
    public List<Product> getProductListBySj() {
        List<Product> prolist = productDao.getProductListBySj();
        for (Product pro: prolist) {
            Classification cl = classificationDao.getFirstId(pro.getPid());
            pro.setId(cl.getPid()+"");
            String nowAmount = Integer.parseInt(pro.getFbk3())-Integer.parseInt(pro.getFbk4())+"";
            pro.setNowAmount(nowAmount);
        }
        return prolist;
    }

    @Override
    public int insertBatchProduct(List<Product> products) {
        long str = System.currentTimeMillis();
        Timestamp curDate = new Timestamp(System.currentTimeMillis());
        for (Product product: products) {
            product.setTradeName("RK"+str);
            product.setCreateTime(curDate);
            product.setGoodsState("上架中");
            product.setGoodStatusId("2");
        }
        int a = productDao.insertBatch(products);
        return a;
    }

    @Override
    public List<Product> findProductList() {
        List<Product> productList = productDao.findProductList();
        return productList;
    }

    @Override
    public int updateBatchProduct(List<Product> products) {
        int flag = productDao.updateBatchProduct(products);
        return 1;
    }

    @Override
    public List<Product> findProductListByNum(Product product) {
        List<Product> productList = productDao.findProductListByNum(product);
        List<Product> newList = new ArrayList<>();
        for (Product pro: productList) {
            pro.setCreateTimeToString(DateUtils.getTimeDay(pro.getCreateTime()));

            ProductOrder order = new ProductOrder();
            order.setFbk5(pro.getTradeName());
            order.setFbk1(product.getProductNum());

            String sum = productDao.getSumAmountByRk(order);
            if(StringUtils.isEmpty(sum)){sum="0";}
            //查看该入库单是否已发完货，发完不现实该入库单信息
            if(Integer.parseInt(pro.getAmount()) - Integer.parseInt(sum) > 0){
                pro.setSysl(Integer.parseInt(pro.getAmount()) - Integer.parseInt(sum)+"");
                newList.add(pro);
            }
        }
        return newList;
    }

}
